package com.geek.controller;

import com.geek.entity.IdEntity;
import com.geek.resp.Response;
import com.geek.services.BaseRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Slf4j
public abstract class BaseController<T extends IdEntity> {

	protected BaseRepository<T> repository;

	protected Example<T> example;

	public void setRepository(BaseRepository<T> repository){
		this.repository = repository;
	}

	public void setExample(Example<T> example){
		this.example = example;
	}

	@RequestMapping(path = "/list")
	public Response list(){
		Response response = new Response(Response.CODE_SUCCESS);

		List<T> list;
		if(example == null){
			list = repository.findAll();
		}else{
			list = repository.findAll(example);
		}
		response.setData(list);
		return response;
	}

	@RequestMapping(path = "/save")
	public Response save(@RequestBody T t){
		Response response = new Response(Response.CODE_SUCCESS);
		T result = repository.save(t);
		log.debug(result.toString());
		response.setData(result);
		return response;
	}

	@RequestMapping(path = "/delete")
	public Response delete(@RequestBody T t){
		Response response = new Response(Response.CODE_SUCCESS);
//		repository.delete(t);
		t.setDelFlag(true);
		repository.save(t);

		return response;
	}

}
